package softswitch.service;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import softswitch.model.Offer;
import softswitch.model.OfferDetail;
import softswitch.model.Route;


@Stateless
public class OfferDetailDAO {

	
	@PersistenceContext(unitName = "persistence")
    private EntityManager em;
	
	
	public OfferDetail getById(Integer id){	
		return  em.find(OfferDetail.class, id);
	}
    
    public OfferDetail save(OfferDetail offerdetail) {
    	em.persist(offerdetail); 
    	return offerdetail;
    }
    
    public OfferDetail update(OfferDetail offerdetail) {
    	return em.merge(offerdetail); 
    }
    
    public void delete(Integer id) {
    	em.remove(em.find(OfferDetail.class, id));	
    }
    	
	@SuppressWarnings("unchecked")
    public List<OfferDetail> list(int first, int max) {    	
    	Query query = em.createQuery("SELECT e FROM OfferDetail e");
    	if (max > 0) {
            query.setMaxResults(max);
        }
        if (first > 0) {
            query.setFirstResult(first);
        }
        return query.getResultList();   
    }
	 
    //--------------------------------------------------------
    
	public OfferDetail getByOfferRoute(Offer offer, Route route) {
		OfferDetail result = null;
		Query query = em.createQuery("SELECT e FROM OfferDetail e WHERE e.offer=:offer AND e.route=:route");
    	query.setParameter("offer", offer);
    	query.setParameter("route", route);
    	try{
    		result = (OfferDetail) query.getSingleResult();
    	}
    	catch(NoResultException e){
    	}
    	return result ;   
	}
	
    @SuppressWarnings("unchecked")
    public List<OfferDetail> listByOffer(Offer offer) {    	
    	Query query = em.createQuery("SELECT e FROM OfferDetail e WHERE e.offer=:offer");
    	query.setParameter("offer", offer);
    	return query.getResultList();   
    }

	@SuppressWarnings("unchecked")
	public List<OfferDetail> listByRoute(Route route) {
		Query query = em.createQuery("SELECT e FROM OfferDetail e WHERE e.route=:route");
    	query.setParameter("route", route);
    	return query.getResultList();   
    }

	
    
    
}

